<script setup>
import {nextTick, onMounted, ref} from "vue";
import axios from "axios";
import {getBaseUrl} from "@/js/common.js";
import {useRoute} from "vue-router";

let text = ref('');
let loading = ref(false)
let titles = ref([])

const route = useRoute()

const preview = ref(null)

onMounted(() => {
  loading.value = true
  axios.get(getBaseUrl('blogHandle')+ `/blog/get/${route.query.id}`).then(res => {
    text.value = res.data.data
    loading.value = false
    extractCatalog()
  })
})

async function extractCatalog() {
  await nextTick()
  const anchors = preview.value.$el.querySelectorAll('h1,h2,h3,h4,h5,h6');
  const filteredTitles = Array.from(anchors).filter((title) => !!title.innerText.trim());
  if (!filteredTitles.length) {
    titles.value = [];
    return;
  }

  const hTags = Array.from(new Set(filteredTitles.map((title) => title.tagName))).sort();

  titles.value = filteredTitles.map((el) => ({
    title: el.innerText,
    lineIndex: el.getAttribute('data-v-md-line'),
    indent: hTags.indexOf(el.tagName),
  }));
}
function handleAnchorClick(anchor){
  const { lineIndex } = anchor;

  const heading = preview.value.$el.querySelector(`[data-v-md-line="${lineIndex}"]`);

  if (heading) {
    // 注意：如果你使用的是编辑组件的预览模式,则这里的方法名改为 previewScrollToTarget
    preview.value.previewScrollToTarget({
      target: heading,
      top: 10,
    });
  }
}
</script>

<template>
  <div v-loading="loading">
    <el-container>
      <el-aside width="200px">
        <el-affix :offset="10">
          <el-scrollbar height="800px">
            <el-anchor
                :offset="30"
            >
              <el-anchor-link v-for="(item,index) in titles" :key="item" :href='`#${index}`' :style="`margin-left: ${item.indent * 20}px`" :title="item.title" @click="handleAnchorClick(item)" />
            </el-anchor>
          </el-scrollbar>
        </el-affix>
      </el-aside>
      <el-main>
        <v-md-editor id="preview" v-model="text" ref="preview" mode="preview"></v-md-editor>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>

</style>
